package cn.ibizlab.todo.util.rest;

import cn.ibizlab.todo.util.client.IBZPMSFeignClient;
import cn.ibizlab.todo.util.errors.BadRequestAlertException;
import cn.ibizlab.todo.util.security.AuthenticationInfo;
import cn.ibizlab.todo.util.security.AuthenticationUser;
import cn.ibizlab.todo.util.security.AuthorizationLogin;
import cn.ibizlab.todo.util.service.AuthenticationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class IBZTodoAuthController extends AuthenticationController {
    @Autowired
    private AuthenticationUserService userDetailsService;


    @Autowired
    private IBZPMSFeignClient pmsFeignClient;

    public ResponseEntity<AuthenticationInfo> login(@Validated @RequestBody AuthorizationLogin authorizationLogin){

        userDetailsService.resetByUsername(authorizationLogin.getUsername());

        String[] data=authorizationLogin.getUsername().split("[|]");
        String loginname=authorizationLogin.getUsername();
        String domains="";

        if(data.length==2) {
            loginname=data[0].trim();
            domains=data[1].trim();
        }

        AuthorizationLogin logininfo = new AuthorizationLogin();
        logininfo.setDomain(domains);
        logininfo.setLoginname(loginname);
        logininfo.setPassword(authorizationLogin.getPassword());
        AuthenticationInfo info = null;
        try{
            info = pmsFeignClient.login(logininfo);
        }catch (Exception ex){
            throw new BadRequestAlertException("登录失败","IBZUAAUser",loginname);
        }

        //final AuthenticationUser authuserdetail = userDetailsService.loadUserByLogin(authorizationLogin.getUsername(),authorizationLogin.getPassword());
        // 生成令牌
        final String token = info.getToken();
        // 返回 token
        return ResponseEntity.ok().body(new AuthenticationInfo(token,info.getUser()));
    }
}
